using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Services;

/// <summary>
/// 短信服务实现
/// </summary>
public class SmsService : ISmsService
{
    private readonly ILogger<SmsService> _logger;
    private readonly IConfiguration _configuration;
    private readonly ICacheService _cacheService;

    public SmsService(
        ILogger<SmsService> logger, 
        IConfiguration configuration,
        ICacheService cacheService)
    {
        _logger = logger;
        _configuration = configuration;
        _cacheService = cacheService;
    }

    /// <summary>
    /// 发送短信验证码
    /// </summary>
    public async Task<bool> SendVerificationCodeAsync(string phoneNumber, string code, string type)
    {
        try
        {
            var message = type switch
            {
                "login" => $"【JGSY】您的登录验证码是：{code}，5分钟内有效。如非本人操作，请忽略此短信。",
                "register" => $"【JGSY】您的注册验证码是：{code}，5分钟内有效。",
                "reset_password" => $"【JGSY】您的密码重置验证码是：{code}，5分钟内有效。如非本人操作，请立即修改密码。",
                _ => $"【JGSY】您的验证码是：{code}，5分钟内有效。"
            };

            // 检查发送频率限制
            var rateLimitKey = $"sms_rate_limit:{phoneNumber}";
            var lastSendTime = await _cacheService.GetAsync<DateTime?>(rateLimitKey);
            if (lastSendTime.HasValue && DateTime.UtcNow.Subtract(lastSendTime.Value).TotalSeconds < 60)
            {
                _logger.LogWarning("SMS发送过于频繁，手机号：{PhoneNumber}", phoneNumber);
                return false;
            }

            // 实际发送短信的逻辑
            var result = await SendSmsAsync(phoneNumber, message);
            
            if (result)
            {
                // 设置发送频率限制
                await _cacheService.SetAsync(rateLimitKey, DateTime.UtcNow, TimeSpan.FromMinutes(1));
                _logger.LogInformation("验证码发送成功，手机号：{PhoneNumber}，类型：{Type}", phoneNumber, type);
            }
            
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发送验证码失败，手机号：{PhoneNumber}，错误：{Error}", phoneNumber, ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 发送短信
    /// </summary>
    public async Task<bool> SendSmsAsync(string phoneNumber, string message)
    {
        try
        {
            // 开发环境下模拟发送
            var environment = _configuration["ASPNETCORE_ENVIRONMENT"] ?? "Production";
            if (environment == "Development")
            {
                _logger.LogInformation("【模拟短信发送】手机号：{PhoneNumber}，内容：{Message}", phoneNumber, message);
                await Task.Delay(500); // 模拟网络延迟
                return true;
            }

            // 生产环境使用实际短信服务商
            // 这里可以集成阿里云短信、腾讯云短信等服务
            var apiUrl = _configuration["SmsService:ApiUrl"];
            var apiKey = _configuration["SmsService:ApiKey"];
            
            if (string.IsNullOrEmpty(apiUrl) || string.IsNullOrEmpty(apiKey))
            {
                _logger.LogWarning("短信服务配置不完整，无法发送短信");
                return false;
            }

            // TODO: 实现具体的短信服务商API调用
            // 例如：using HttpClient调用短信服务商API
            
            _logger.LogInformation("短信发送成功，手机号：{PhoneNumber}", phoneNumber);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "短信发送失败，手机号：{PhoneNumber}，错误：{Error}", phoneNumber, ex.Message);
            return false;
        }
    }
}

/// <summary>
/// 邮件服务实现
/// </summary>
public class EmailService : IEmailService
{
    private readonly ILogger<EmailService> _logger;
    private readonly IConfiguration _configuration;

    public EmailService(ILogger<EmailService> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    /// <summary>
    /// 发送密码重置邮件
    /// </summary>
    public async Task<bool> SendPasswordResetEmailAsync(string email, string resetCode)
    {
        try
        {
            var subject = "【JGSY CMS】密码重置验证码";
            var body = $@"
<html>
<body>
    <h2>密码重置验证码</h2>
    <p>您好！</p>
    <p>您正在进行密码重置操作，验证码为：</p>
    <h3 style='color: #007bff; font-size: 24px;'>{resetCode}</h3>
    <p>验证码有效期为15分钟，请及时使用。</p>
    <p>如果这不是您本人的操作，请忽略此邮件。</p>
    <br/>
    <p>此邮件由系统自动发送，请勿回复。</p>
    <p>JGSY CMS 团队</p>
</body>
</html>";

            return await SendEmailAsync(email, subject, body);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发送密码重置邮件失败，邮箱：{Email}，错误：{Error}", email, ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 发送邮件
    /// </summary>
    public async Task<bool> SendEmailAsync(string email, string subject, string body)
    {
        try
        {
            // 开发环境下模拟发送
            var environment = _configuration["ASPNETCORE_ENVIRONMENT"] ?? "Production";
            if (environment == "Development")
            {
                _logger.LogInformation("【模拟邮件发送】收件人：{Email}，主题：{Subject}", email, subject);
                await Task.Delay(300); // 模拟网络延迟
                return true;
            }

            // 生产环境使用实际邮件服务
            var smtpHost = _configuration["EmailService:SmtpHost"];
            var smtpPort = _configuration["EmailService:SmtpPort"];
            var username = _configuration["EmailService:Username"];
            var password = _configuration["EmailService:Password"];

            if (string.IsNullOrEmpty(smtpHost) || string.IsNullOrEmpty(username))
            {
                _logger.LogWarning("邮件服务配置不完整，无法发送邮件");
                return false;
            }

            // TODO: 实现具体的邮件发送逻辑
            // 可以使用 MailKit 或 System.Net.Mail 等库
            
            _logger.LogInformation("邮件发送成功，收件人：{Email}，主题：{Subject}", email, subject);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "邮件发送失败，收件人：{Email}，错误：{Error}", email, ex.Message);
            return false;
        }
    }
}
